<?php
$di = \Phalcon\Di::getDefault();

$di->getShared('eventsManager')->attach('entity:links', function ($event, \Core\Mvc\Entity\EntityInterface $entity, $links) {
    if ($entity->getEntity() == 'configList' && $entity->getContentModel() == 'region') {
        $links['addBlock'] = array(
            'href' => array(
                'for' => 'adminRegionBlockAddList',
                'region' => $entity->getId(),
            ),
            'data-target' => 'right_handle',
            'icon' => 'info',
            'name' => '添加区块'
        );
        $links['sortBlock'] = array(
            'href' => array(
                'for' => 'adminRegionBlockSort',
                'region' => $entity->getId(),
            ),
            'data-target' => 'right_handle',
            'icon' => 'info',
            'name' => '区块列表'
        );
        $entity->setLinks($links);
    }
});

function regionList()
{
    $di = \Phalcon\Di::getDefault();
    $regionListData = $di->getShared('config')->get('m.region.list');
    $output = array();
    foreach ($regionListData as $key => $value) {
        $output[$key] = $value['name'];
    }
    return $output;
}

function regionRender($region)
{
    $di = \Phalcon\Di::getDefault();
    $themes = $di->getShared('config')->get('themes');
    $controllerName = $di->getShared('dispatcher')->getControllerName();
    $currentTheme = $themes[ucfirst($controllerName)];
    $regionData = $di->getShared('entityManager')->get('region', ['theme' => $currentTheme, 'region' => $region]);
    if (!$regionData) {
        return false;
    }
    $data = $di->getShared('entityManager')->find('block', ['theme' => $currentTheme, 'region' => $region]);
    $output = [
        '#templates' => ['region', 'region-' . $region],
        '#module' => 'region',
        'data' => $data,
        'regionData' => $regionData,
        'regionId' => $region
    ];
    return $output;
}

function blockRender($block, $region)
{
    $di = \Phalcon\Di::getDefault();
    if (!is_array($block['contentModel']) && !isset($block['contentModel'])) {
        throw new \Exception('区块数据不合法');
    }
    if ($di->getShared('security')->access($block) === false) {
        return '';
    }
    $contentModel = $block['contentModel'];
    $blockContentModelList = $di->getShared('config')->get('m.region.entityBlockContentModelList');
    if (!isset($blockContentModelList[$contentModel])) {
        throw new Exception("区块类型不存在");
    }
    if (!isset($blockContentModelList[$contentModel]['class'])) {
        $block['#templates'] = array(
            'block',
            'block-' . $contentModel,
            'block-' . $region,
            'block-' . $region . '-' . $contentModel,
            'block-' . $region . '-' . $block['id']
        );
        $block['#module'] = 'region';
        return $block;
    } else {
        $contentModelClass = $blockContentModelList[$contentModel];
        $output = new $contentModelClass($block);
        return $output;
    }
}